import React, { useEffect, useState } from 'react'
import Head from 'next/head'
import { Tabs, Row, Col, Skeleton, Empty, List, message, Tooltip, Button, Avatar, Popover } from 'antd'
import { useRouter } from 'next/router'
import messageModel from 'pages/model/message'
import Header from '@/components/header/header'
import { storage } from '@/utils/utils'
import PopoverCard from 'pages/popover-card'
import Link from 'next/link'
import userInfoModel from 'pages/model/user-info'
import categoriesListModel from 'pages/model/categories-manage'
import articlesModel from 'pages/model/articles'
import ListItem from '@/components/list-item/list-item'
import noData from '@/public/images/no-data.svg'
import styles from '@/styles/Home.module.scss'

const { TabPane } = Tabs

function Home () {
  const router = useRouter()
  const { word } = router.query
  const [dataLoding, setDataLoding] = useState(true)
  const [articlesListData, setArticlesListData] = useState([])
  const [userListData, setUserListData] = useState([])
  const [tagsListData, setTagsListData] = useState([])
  const [updateStatus, setUpdateStatus] = useState(false)
  useEffect(() => {
    if (word) {
      if (JSON.parse(storage.get('next_blog_userInfo'))?.id) {
        setDataLoding(true)
        articlesModel.getArticlePageList({
          data: {loginId: JSON.parse(storage.get('next_blog_userInfo'))?.id, title: word}
        }).then(({datas}) => {
          if (datas && datas.list) {
            setArticlesListData(datas.list)
            setDataLoding(false)
          }
        })
      }
    }
  }, [word])
  // 标签搜索
  useEffect(() => {
    if (word) {
      if (JSON.parse(storage.get('next_blog_userInfo'))?.id) {
        setDataLoding(true)
        categoriesListModel.getTagsList({
          data: { name: word}
        }).then(({datas}) => {
          if (datas && datas.list) {
            datas.list.forEach(item => {
              const tagName = item.name.toLowerCase()
              const substr = `/${word.toLowerCase()}/g`
              item.name = tagName.replace(eval(substr), `<span style='color:red;font-weight:bold'>${word}</span>`)
            })
            setTagsListData(datas.list)
            setDataLoding(false)
          }
        })
      }
    }
  }, [word])
  
  useEffect(() => {
    if (word) {
      if (JSON.parse(storage.get('next_blog_userInfo'))?.id) {
        setDataLoding(true)
        userInfoModel.searchUserList({
          data: {loginId: JSON.parse(storage.get('next_blog_userInfo'))?.id, name: word}
        }).then(({datas}) => {
          if (datas && datas.list) {
            datas.list.forEach(item => {
              const userName = item.username
              const substr = `/${word}/g`
              item.usernameColor = userName.replace(eval(substr), `<span style='color:red;font-weight:bold'>${word}</span>`)
            })
            console.log(datas.list)
            setUserListData(datas.list)
            setDataLoding(false)
          }
        })
      }
    }
  }, [word, updateStatus])

  const replaceUserRelationship = (userId, status) => {
    if (status === 0) {
      messageModel.addMessage({
        data: {
          userId,
          loginId: JSON.parse(storage.get('next_blog_userInfo'))?.id,
          type: 1
        }
      }).then(data => {
        console.log(data)
      })
    }
    userInfoModel.replaceUserRelationship({
      data: {
        id: userId,
        loginId: JSON.parse(storage.get('next_blog_userInfo'))?.id,
        status: status === 1 ? 0 : 1
      }
    }).then(data => {
      if (data.success) {
        message.destroy()
        message.success(data.message)
        setUpdateStatus(!updateStatus)
      }
    })
  }
  return (
    <div className={styles.container}>
      <Head>
        <title>Le-Yi</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Header searchWord={word} />
      <Row justify="center" style={{background: '#fff', width: 1000, margin: '20px auto'}} >
        <Col xs={24} sm={24} md={20} lg={20}>
          <Tabs defaultActiveKey="1">
            <TabPane tab="文章" key="1">
              {
                dataLoding ?
                  <div className={styles.skeleton}>
                    <Skeleton active />
                    <Skeleton.Image  className={styles.skeleton_img} />
                  </div>
                  : 
                  <>
                    {articlesListData.length && articlesListData.length > 0 ?
                      <>
                        {articlesListData.map((item, index) => <ListItem key={index} searchWord={word} data={item} />)}
                      </>
                      :
                      <Empty
                        // 这是个坑 noData是一个对象 {src, height, width}
                        image={noData.src}
                        imageStyle={{
                          height: 100,
                        }}
                        description={
                          <span style={{color: '#808795'}}>暂无数据</span>
                        }
                      >
                      </Empty>
                    }
                    
                  </>
              }
            </TabPane>
            <TabPane tab="标签" key="2">
              {
                dataLoding ?
                  <div className={styles.skeleton}>
                    <Skeleton active />
                    <Skeleton.Image  className={styles.skeleton_img} />
                  </div>
                  : 
                  <>
                    {tagsListData.length && tagsListData.length > 0 ?
                      <>
                        <List
                          itemLayout="horizontal"
                          dataSource={tagsListData}
                          renderItem={item => (
                            <List.Item>
                              <List.Item.Meta
                                avatar={<Avatar src={item.imgUrl} />}
                                title={<div dangerouslySetInnerHTML={{__html: item.name}}></div>}
                                description={item.introduce}
                              />
                            </List.Item>
                          )}/>
                      </>
                      :
                      <Empty
                        // 这是个坑 noData是一个对象 {src, height, width}
                        image={noData.src}
                        imageStyle={{
                          height: 100,
                        }}
                        description={
                          <span style={{color: '#808795'}}>暂无数据</span>
                        }
                      >
                      </Empty>
                    }
                    
                  </>
              }
            </TabPane>
            <TabPane tab="用户" key="3">
              {
                dataLoding ?
                  <div className={styles.skeleton}>
                    <Skeleton active />
                    <Skeleton.Image  className={styles.skeleton_img} />
                  </div>
                  : 
                  <>
                    {userListData.length > 0 ?
                      <List
                        itemLayout="horizontal"
                        dataSource={userListData}
                        renderItem={item => (
                          <List.Item actions={[
                            (JSON.parse(storage.get('next_blog_userInfo'))?.id === item.id) ?
                              <Link prefetch href="/my-info"><Button style={{background: '#fff', borderColor: '#8590a6', width: 110, height: 34, color: '#8590a6'}}  type="primary" >我的主页</Button></Link>
                              : <Tooltip key="btn" title={item.mutualConcern === 1 ? '取消关注' : '关注Ta'}> <Button style={{background: '#8590a6', borderColor: '#8590a6', width: 110, height: 34}} onClick={() => replaceUserRelationship(item.id, item.mutualConcern)}  type="primary" >{item.mutualConcern === 1 ? '已关注' : '关注'}</Button></Tooltip>
                          ]}>
                            <List.Item.Meta
                              avatar={<Popover destroyTooltipOnHide={true} content={<PopoverCard avatar={item.avatar} type={0} username={item.username} job={item.job} city={item.city} province={item.province} id={item.id} setFn={setUpdateStatus} status={updateStatus}></PopoverCard>}><Avatar src={item.avatar} /></Popover>}
                              title={<Link prefetch href={{pathname: '/user-info', query: {id: item.id}}}>
                                <div dangerouslySetInnerHTML={{__html: item.usernameColor}}></div>
                              </Link>}
                              description={<span>{item.province} · {item.city} 丨{item.job}</span>}
                            />
                          </List.Item>
                        )}
                      />
                      :
                      <Empty
                        // 这是个坑 noData是一个对象 {src, height, width}
                        image={noData.src}
                        imageStyle={{
                          height: 100,
                        }}
                        description={
                          <span style={{color: '#808795'}}>暂无数据</span>
                        }
                      >
                      </Empty>
                    }
                    
                  </>
              }
            </TabPane>
          </Tabs>
        </Col>
      </Row>
    </div>
  )
}

export default  Home